/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.nonmember;

import entity.MemberCustomer;
import entity.Product;
import entity.SaleOrder;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.UserTransaction;
import model.ItemCart;
import model.ShoppingCart;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import service.ProductServiceLocal;
import service.SaleOrderDetailServiceLocal;
import service.SaleOrderServiceLocal;

/**
 *
 * @author SONY
 */
public class OrderStep3StrutsAction extends org.apache.struts.action.Action {
    
    @EJB SaleOrderServiceLocal saleOrderServiceLocal;
    @EJB SaleOrderDetailServiceLocal saleOrderDetailServiceLocal;
    @EJB ProductServiceLocal productServiceLocal;
    
    private UserTransaction ut;


    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String fullName = "";
        String address = "";
        String phone = "";
        String paymenttype = "";
        try {
            String btnSubmit = request.getParameter("btnSubmit");
            fullName = request.getParameter("fullname");
            address = request.getParameter("address");
            phone = request.getParameter("phone");  
            paymenttype = request.getParameter("paymenttype");
            String status = "Mới Đặt";
            HttpSession session = request.getSession();
            ShoppingCart shopping_cart = (ShoppingCart) session.getAttribute("shopping_cart");
            if(shopping_cart.getQuantityItemCart() > 0) {
                if(btnSubmit == null) {
                    return mapping.findForward("error");
                } else if(btnSubmit.equals("Thay Đổi")) {
                    request.setAttribute("Name", fullName);
                    request.setAttribute("Address", address);
                    request.setAttribute("Phone", phone);
                    return mapping.findForward("change");
                } else if(btnSubmit.equals("Xác Nhận")) {
                    if(paymenttype.equals("Cash")) {
                        BigDecimal Total = new BigDecimal(shopping_cart.TotalPrice());
                        ArrayList<ItemCart> lstItemCart = shopping_cart.getAllItemCart();
                        Date OrderDate  = new Date();
                        MemberCustomer member = null;
                        if(session.getAttribute("user_member") != null) {
                            member = (MemberCustomer) session.getAttribute("user_member");
                        }
                        Context ctx = new InitialContext();
                        ut = (UserTransaction) ctx.lookup("java:comp/UserTransaction");
                        ut.begin(); //start the transactions
                        ServletContext context = servlet.getServletContext();
                        saleOrderServiceLocal = (SaleOrderServiceLocal) context.getAttribute("saleOrderServiceLocal");
                        saleOrderDetailServiceLocal = (SaleOrderDetailServiceLocal) context.getAttribute("saleOrderDetailServiceLocal");
                        productServiceLocal = (ProductServiceLocal) context.getAttribute("productServiceLocal");
                        SaleOrder saleorder = saleOrderServiceLocal.addSaleOrder(member, fullName, address, phone, OrderDate, status, Total, paymenttype);
                        if(saleorder != null) {
                            for(int i = 0; i < lstItemCart.size(); i++) {
                                String ProductID = lstItemCart.get(i).getProductID();
                                int OrderQty = lstItemCart.get(i).getQuantity();
                                BigDecimal LineTotal = new BigDecimal(lstItemCart.get(i).getTotalLine());
                                if(saleOrderDetailServiceLocal.addSaleOrderDetail(saleorder, ProductID, OrderQty, LineTotal)) {
                                    //cập nhật lại sl hàng tồn kho khi đặt hàng thành công
                                    Product product = productServiceLocal.getProductDetails_byPID(ProductID);
                                    int QOH = product.getQoh();
                                    int QOH_new = QOH - OrderQty;
                                    if(productServiceLocal.updateQOH_byPID(ProductID, QOH_new)) {
                                        System.out.println("inserted successful!");
                                    }
                                }
                            }
                        }
                        ut.commit(); //end the transaction
                        shopping_cart.makeEmpty();
                        return mapping.findForward("success_cash");
                    } else {
                        request.setAttribute("Name", fullName);
                        request.setAttribute("Address", address);
                        request.setAttribute("Phone", phone); 
                        return mapping.findForward("success_creditcard");
                    }
                }
            } else {
                return mapping.findForward("error");
            }
        } catch (Exception e) {
            System.err.println(e);
            //ut.rollback();
        }
        request.setAttribute("Name", fullName);
        request.setAttribute("Address", address);
        request.setAttribute("Phone", phone);
        request.setAttribute("PaymentType", paymenttype);
        request.setAttribute("error", "Đặt Hàng Thất Bại Do Bị Gián Đoạn. Hãy Đặt Hàng Lại Sau!");
        return mapping.findForward("error_rollback");
    }
}
